package red.internal.client.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import red.internal.core.message.Message;
import red.internal.core.message.Protocol;
import red.internal.core.message.RegistryCommand;
import red.internal.core.message.RegistryMessage;

import java.util.concurrent.ExecutorService;

/**
 * @author Jin Zheng
 * @since 2019-05-12
 */
public class DefaultMessageListener implements MessageListener
{
	private static Logger logger = LoggerFactory.getLogger(DefaultMessageListener.class);

	private MessageListener registryListener;
	private MessageListener cacheListener;
	private final ExecutorService executorService;
	private final HandlerClient handlerClient;

	public DefaultMessageListener(ExecutorService executorService, HandlerClient handlerClient)
	{
		this.executorService = executorService;
		this.handlerClient = handlerClient;
	}

	@Override
	public void complete(Message message)
	{
		if (message.getProtocol() == Protocol.REGISTRY && registryListener != null)
		{
			executorService.submit(() ->
			{
				registryListener.complete(message);
				RegistryMessage registryMessage = (RegistryMessage) message;
				if (registryMessage.getCommand() == RegistryCommand.NOTIFY)
				{
					RegistryMessage response = registryMessage.success();
					handlerClient.sendMessage(response);
				}
			});
		}
		else if (message.getProtocol() == Protocol.CACHE && cacheListener != null)
		{
			executorService.submit(() -> cacheListener.complete(message));
		}
	}

	public void setRegistryListener(MessageListener registryListener)
	{
		this.registryListener = registryListener;
	}

	public void setCacheListener(MessageListener cacheListener)
	{
		this.cacheListener = cacheListener;
	}

}
